<?php

namespace backend\controllers;

use Yii;
use common\models\project\Project;
use common\models\project\ProjectSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use common\models\adminlog\AdminLog;
use zhongkefu\zhongkefu;
use common\models\projectpaid\ProjectPaid;
use common\models\projectpaid\ProjectPaidSearch;

/**
 * ProjectController implements the CRUD actions for Project model.
 */
class ProjectController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Project models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProjectSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Project model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $model->starttime = date('Y-m-d H:i:s', $model->starttime);
        $model->endtime = date('Y-m-d H:i:s', $model->endtime);
        $model->file = json_decode($model->file);
        $model->filename = json_decode($model->filename);

        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new Project model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Project();

        if ($model->load(Yii::$app->request->post())) {
            //事物回滚
            $transaction = \Yii::$app->db->beginTransaction();
            try {

                $siteRoot =  Yii::$app->params['articleimg'];

                if (!empty($_FILES)) {

                    if($_FILES['file']['tmp_name']){

                        $tempPath = $_FILES['file']['tmp_name'];
                        $arrname = array();
                        foreach ($_FILES['file']['name'] as $k=>$t) {
                           
                            $temp = $tempPath[$k];
                         
                            $filesName = !empty($t) ? uniqid() . '.' . pathinfo($t, PATHINFO_EXTENSION) : '';
                            $arrname[] = $filesName;
                            $uploadPath = $siteRoot . $filesName;
                            move_uploaded_file($temp, $uploadPath);

                        }
                        
                        $model->file = json_encode($arrname);
                    }
                }
                $model->filename = json_encode(Yii::$app->request->post()['Project']['filename']);
                $model->starttime = strtotime(Yii::$app->request->post()['Project']['starttime']);
                $model->endtime = strtotime(Yii::$app->request->post()['Project']['endtime']);
                $ok = $model->save();
                if (!$ok) {
                    throw new ErrorException('新增项目失败', 1002);
                }

                $ok = Yii::$app->db->createCommand()->insert('project_repo', [
                    'pr_id' => $model->id,
                ])->execute();
                if (!$ok) {
                    throw new ErrorException('生成项目申报表失败', 1002);
                }

                $ok = Yii::$app->db->createCommand()->insert('project_contract', [
                    'pr_id' => $model->id,
                ])->execute();
                if (!$ok) {
                    throw new ErrorException('生成项目合同表失败', 1002);
                }


                $ok = Yii::$app->db->createCommand()->insert('project_summary', [
                    'pr_id' => $model->id,
                ])->execute();
                if (!$ok) {
                    throw new ErrorException('生成项目总结报告表失败', 1002);
                }


                $transaction->commit();
                Yii::$app->getSession()->setFlash('success', '新增项目成功');
                return $this->redirect(['view', 'id' => $model->id]);

            } catch (\Exception $e) {

                $transaction->rollBack();
                $remark = $e->getMessage();
                Yii::$app->getSession()->setFlash('error', $remark);

                return $this->render('create', [
                    'model' => $model,
                ]);
            }
            
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Project model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {

            $model->starttime = strtotime(Yii::$app->request->post()['Project']['starttime']);
            $model->endtime = strtotime(Yii::$app->request->post()['Project']['endtime']);

            $siteRoot =  Yii::$app->params['articleimg'];

            if (!empty($_FILES)) {

                if($_FILES['file']['tmp_name']) {

                    $tempPath = $_FILES['file']['tmp_name'];
                    $arrname = array();
                    foreach ($_FILES['file']['name'] as $k=>$t) {

                        if ($t == '') {
                            $arrname[] = Yii::$app->request->post()['Project']['file'][$k];
                        } else {
                            $temp = $tempPath[$k];
                            $filesName = uniqid() . '.' . pathinfo($t, PATHINFO_EXTENSION);
                            $arrname[] = $filesName;
                            $uploadPath = $siteRoot . $filesName;
                            move_uploaded_file($temp, $uploadPath);
                        }
                    }
                        
                    $model->file = json_encode($arrname);
                }

            }

            $model->filename = json_encode(Yii::$app->request->post()['Project']['filename']);

            if ($model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        } else {
            // var_dump($model);die;
            $model->file = json_decode($model->file);
            $model->filename = json_decode($model->filename);
            $model->starttime = date('Y-m-d H:i:s', $model->starttime);
            $model->endtime = date('Y-m-d H:i:s', $model->endtime);
            $filenum = count($model->filename);
            return $this->render('update', [
                'model' => $model,
                'filename' => $filenum,
            ]);
        }
    }

    /**
     * Deletes an existing Project model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Project model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Project the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Project::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionStart()
    {
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);
            foreach($ids as $id){
                $model = Project::findOne(['id' => $id]);
                Project::updateAll(['status'=>Project::STATUS_ACTIVE],['id' =>$model->id]);
            }
            return true;
        }
    }

    /**
     * 停用按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionStop()
    {
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);
            foreach($ids as $id){
                $model = Project::findOne(['id' => $id]);
                Project::updateAll(['status'=>Project::STATUS_INACTIVE],['id' =>$model->id]);
            }
            return true;
        }
    }

    /**
     * 删除按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionAlldelete()
    {
        $artname="";
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);

            foreach($ids as $val){
                $models = Project::findOne(['id' => $val]);
                $artname .= $models->name.",";
            }
            $artname = substr($artname,0,-1);
            
            foreach($ids as $id){
                $model = Project::findOne(['id' => $id]);
                $this->findModel($id)->delete();

            }

            Adminlog::addlog(yii::$app->user->id, '批量删除项目 '.$artname);
            return true;
        }
    }

}
